<template>
  <el-card class="container">
    <el-row type="flex" justify="space-between" class="mb10">
      <el-col>
        <el-button size="small" @click="handleBack">返回上一页</el-button>
        <span style="font-weight: bold; margin-left: 10px">{{ title }}</span>
      </el-col>
      <div>
        <el-button type="primary" size="mini" @click="handleSubmit">提交</el-button>
      </div>
    </el-row>
    <div class="content">
      <el-form :model="form" :rules="rules" ref="form" label-width="160px" size="small">
        <el-card header="配比基本信息" :borderd="false" shadow="never" :body-style="{ padding: 20 }" class="mb10">
          <el-row>
            <el-col :span="12">
              <el-form-item label="配比名称" prop="ratioName">
                <el-input v-model="form.ratioName" placeholder="请输入配比名称" />
              </el-form-item>

              <el-form-item label="搅拌时间" prop="stirringTime">
                <el-input v-model="form.stirringTime" placeholder="请输入搅拌时间" />
              </el-form-item>
              <el-form-item label="盘方量" prop="squareMeasure">
                <el-input v-model="form.squareMeasure" placeholder="请输入盘方量" />
              </el-form-item>
              <el-form-item label="单方容量" prop="unilateralCapacity">
                <el-input v-model="form.unilateralCapacity" placeholder="请输入单方容量" />
              </el-form-item>
              <el-form-item label="水胶比" prop="waterBinderRatio">
                <el-input v-model="form.waterBinderRatio" placeholder="请输入水胶比" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主标号" prop="primaryDesignatorId">
                <el-select v-model="form.primaryDesignatorId" placeholder="请选择" @change="handlePrimaryIdChange">
                  <el-option style="width: 220px" v-for="(item, index) in PrimaryNameList" :value="item.id" :key="index"
                    :label="item.name"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出机坍稠" prop="outletThickened">
                <el-select v-model="form.outletThickened" placeholder="请选择">
                  <el-option value="80" label="80"></el-option>
                  <el-option value="200" label="200"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出机温度" prop="temperature">
                <el-input v-model="form.temperature" placeholder="请输入出机温度" />
              </el-form-item>
              <el-form-item label="砂率" prop="sandRatio">
                <el-input v-model="form.sandRatio" placeholder="请输入砂率" />
              </el-form-item>
              <el-form-item label="外加剂参量" prop="admixtureParameter">
                <el-input v-model="form.admixtureParameter" placeholder="请输入外加剂参量" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card header="原材料信息" :borderd="false" shadow="never" :body-style="{ padding: 20 }" class="mb10">
          <el-table :data="tableData">
            <el-table-column v-for="(item1, index1) in tableColData" :key="index1" align="center" prop=""
              :label="item1.name">
              <el-table-column v-for="(item2, index2) in item1.children" :key="index2" :prop="item2.prop"
                :label="item2.name" align="center" width="100px">
                <template #default="scope">
                  <div v-if="scope.$index === 0">
                    <el-button v-if="scope.row[item2.id]" class="close-button" @click="handlerClick(item2.id, true)"
                      size="small">
                      {{ scope.row[item2.id] }} <i class="el-icon-close"></i>
                    </el-button>
                    <el-button v-else @click="handlerClick(item2.id)" size="small">选择原料</el-button>

                  </div>
                  <div v-else>
                    <el-input type="number" v-model="scope.row[item2.id]" placeholder="请输入数字"></el-input>
                  </div>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card header="其他信息" class="mt10" v-if="form.id">
          <el-row>
            <el-col :span="12">
              <el-form-item label="配比编号" prop="ratioNo">
                <el-input v-model="form.ratioNo" placeholder="请输入配比编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新时间" prop="updateTime">
                <el-input v-model="form.updateTime" placeholder="请输入更新时间" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新人" prop="createBy">
                <el-input v-model="form.createBy" placeholder="请输入更新人" />
               </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>
    <custom-dialog :dialogCategoryId.sync="dialogCategoryId" :dialog-visible.sync="dialogVisible"
      @onClose="dialogVisible = false" @onSubmit="handleDialogSubmit" />
  </el-card>

</template>

<script>
  import {
    addRatio,
    updateRatio,
    getRatioDetail,
    getMaterialCodeList
  } from "@/api/service/qualityCenter";
  import {
    listDesignator
  } from "@/api/service/main";
  import CustomDialog from "./components/dialog.vue"
  import {
    updateOrders,
    getOrders,
    addOrders,
    // addRepair,
    // updateRepair,
  } from "@/api/service/arrive/enter.js";
  import { transMateriaArrayToObj } from "@/utils/index.js";
  export default {
    components: {
      CustomDialog
    },
    data() {
      return {
        dialogVisible: false,
        dialogCategoryId: null,
        contraVisible: false,
        information: [],
        originData: [{
          "categoryId": 2, // 码表分类ID:2 name:"水1"
          "categoryName": "水1",
          "id": 0,
          "materialId": 0,
          "materialName": "",
          "ratioId": 0,
          "value": 111,
        }, ],
        tableData: [{},{}],
        allUser: [],
        form: {
          id: null,
          ratioNo: null,
          ratioName: null,
          primaryDesignatorId: null,
          primaryName: null,
          stirringTime: null,
          outletThickened: null,
          unilateralCapacity: null,
          waterBinderRatio: null,
          sandRatio: null,
          admixtureParameter: null,
          squareMeasure: null,
          temperature: null,
          updateBy: null,
          updateTime: null,
          remark: '2211',
          status: null,
          informationDTOS: [],
        },
        rules: {
          ratioName: [{
            required: true,
            message: "请填写配比名称",
            trigger: "change"
          }, ],
          primaryDesignatorId: [{
            required: true,
            message: "请选择主标号",
            trigger: "change"
          }, ],
          stirringTime: [{
            required: true,
            message: "请选搅拌时间",
            trigger: "change"
          }, ],
          outletThickened: [{
            required: true,
            message: "请选择出机坍稠",
            trigger: "change"
          }, ],
        },
        PrimaryNameList: [],
        tableColData: [], //原材料表头-原料码表信息tree数据
      };
    },

    created() {
      this.getPrimaryNameList();
      this.getMaterialCodeTreeList();
      let id = this.$route.query.id;
      if (id) {
       this.getInfo(id);
      }
    },
    mounted() {
      for (let index = 0; index < 16; index++) {
        this.originData.push(this.originData[0])

      }
    },
    computed: {
      title() {
        return !this.$route?.query?.id ? "新增标准配比" : "修改标准配比";
      },
    },
    methods: {
      // 获取信息
      getInfo(id) {
        if (id) {
         getRatioDetail(id).then((res) => {
           this.form =  res.data;
           this.information =  res.data.informationDTOS;
           console.log('this.information')

            // if (this.information) {
            //   for (let i = 0; i < this.information.length; i++) {
            //      this.$set(this.tableData[0], this.information[i]?.categoryId, this.information[i].materialName)
            //      this.$set(this.tableData[1], this.information[i]?.categoryId, this.information[i]?.value)
            //     }
            // }
            // 转换数组为对象,供表单添加原料使用
            this.tableData = transMateriaArrayToObj(this.information); 
           console.log(this.tableData)
         });
        }
      },
      /**
       * 获取主要名称列表
       * 该函数没有参数。
       */
      getPrimaryNameList() {
        // 使用listDesignator函数进行请求，分页参数为第1页，每页1000条
        listDesignator({
          pageNum: 1,
          pageSize: 1000
        }).then((res) => {
          this.PrimaryNameList = res?.rows;
          console.log('res', this.PrimaryNameList); // 打印请求结果
        });
      },
      /**
       * 获取用料码表列表
       * 该函数没有参数。
       */
      getMaterialCodeTreeList() {
        getMaterialCodeList().then((res) => {
          this.tableColData = res?.data;
          /*
          let information = [];
          let tableData = [];
          let tableData2 = [];

          for (let i = 0; i < this.tableColData.length; i++) {
            if (this.tableColData[i].children) {
              for (let i2 = 0; i2 < this.tableColData[i].children.length; i2++) {

                tableData[this.tableColData[i].children[i2].id] = '';
                tableData2[this.tableColData[i].children[i2].id] = '';

                information.push({
                  categoryId: this.tableColData[i].children[i2].id,
                  categoryName: this.tableColData[i].children[i2].name,
                  ratioId: this.form.id
                })
              }
            }
          }
          //this.tableData.push(tableData);
          //this.tableData.push(tableData2);
          console.log(this.tableData);
          //this.information = information;
          */
        });
      },


      handleBack() {
        this.$router.push({
          path: "/qualityCenter/ratioManage/ratio",
        });
      },

      // 删除
      handelDelete(obj) {},
      // 运费
      handleSetFreight(obj) {
        this.$refs.setfreight.handelInit(obj);
      },
      handlePrimaryIdChange() {
        this.PrimaryNameList.forEach((item) => {
          if (item.id === this.form.primaryDesignatorId) {
            this.form.primaryName = item.name;
          }
        });
        console.log('this.form', this.form);
      },
      addNumberRules() {
        // 需要添加不可为负数的检验字段
        const numberRules = [
          "bgmd",
          "dldykzddj",
          "kzddjykzzj",
          "kdf",
          "mdf",
          "ksdj",
          "klsydj",
          "kllzstdj",
          "kllzstdjdtlf",
          "kthxndj",
          "zmsxndjyxn",
          "tsxs",
          "kzdj",
          "gmddj",
          "xsldj",
          "fhdj",
          "cd",
          "bsl",
          "kdxqdssl",
          "kdxzlssl",
          "njlsqd",
          "ssl",
          "ksdj",
        ];
        numberRules.forEach((item) => {
          this.rules[item] = [{
            validator: (rule, value, callback) => {
              console.log(rule);
              if (Object.is(Number(value), NaN)) {
                callback(new Error("请输入数字"));
              }
              if (+value < 0) {
                callback(new Error("不能为负数"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          }, ];
        });
      },
      handleSubmit() {
        this.form.informationDTOS = this.information;
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.id) {
              updateRatio({
                ...this.form,
              }).then((res) => {
                this.$message.success("更新成功");
                this.$router.push({
                  path: "/purchase/contract/index"
                });
              });
            } else {
              addRatio({
                ...this.form,
              }).then((res) => {
                this.$message.success("新增成功");
                this.$router.push({
                  path: "/purchase/contract/index"
                });
              });
            }
          } else {
            return false;
          }
        });
      },
      handlerClick(id, isDelete) {
        if (isDelete) {
          this.$confirm("确定要删除该原料吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
            .then(() => {
              console.log('isDelete', isDelete);
              //this.tableData[0][id] = "";
              this.$set(this.tableData[0], id, '')
              // 具体逻辑
            })
            .catch(() => {});
          return;
        }
        // 打开add原材料弹窗
        this.dialogCategoryId = id;
        this.dialogVisible = true;
      },
      handleDialogSubmit(r) {
        console.log('r', r);
        
        this.$set(this.tableData[0], r.id, r.row.name)
        for (let i = 0; i < this.information.length; i++) {
          if (this.information[i].categoryId === r.id) {
            this.information[i].materialId = r.row.id;
            this.information[i].materialName = r.row.name;
          }
        }
        console.log(this.form)
      },
    },
  };
</script>
<style lang="scss" scoped>
  .origin_add_info {
    display: flex;
    justify-content: end;
    align-items: end;
    padding-bottom: 10px;
  }

  .container {
    height: 100%;

    ::v-deep.el-card__body {
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

    .content {
      flex: 1;
      overflow-x: hidden;
      overflow-y: auto;
    }
  }

  ::v-deep .el-select {
    width: 100%;
  }
</style>
